/**
 * @Author: 魏巍
 * @Date:   2018-09-26T02:32:33+08:00
 * @Email:  524314430@qq.com
 * @Filename: index.js
 * @Last modified by:   魏巍
 * @Last modified time: 2018-09-26T02:43:56+08:00
 * @Copyright: free
 */

require('dotenv').config()
const jwt = require('jsonwebtoken')

class Token {

  constructor(secret) {
    this._secret = secret || process.env.JWT_SECRET
  }

  set secret(secret) {
    this._secret = secret
  }

  create(user) {
    if (!user || user.id || user.app_secret) {
      return 'params is error'
    }
    const token = jwt.sign({
        id: user.id,
        secret: user.app_secret
      },
      this._secret, {
        expiresIn: 3600
      })

    return token
  }

  verify(ctx) {
    if (ctx.request.header['authorization']) {
      let token = ctx.request.header['authorization'].split(' ')[1]
      //解码token
      let decoded = jwt.decode(token, this._secret)
      //console.log(decoded);的输出 ：{ user_id: '123123123', iat: 1494405235, exp: 1494405235 }
      if (token && decoded.exp <= new Date() / 1000) {
        ctx.
        ctx.body = {
          message: ''
        }
        return {
          status: 401,
          message: 'token已过期'
        }
      }
      return {
        status: 1,
        message: '验证成功'
      }
    } else {
      return {
        status: 401,
        message: '没有token'
      }
    }
  }
}
